import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import cart from "../../../../store/cart";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: cart,
    fields: ['cartList'],
    actions: ['addCart', 'reduceCart'],
  }],
  properties: {
    goods: Object,
    showSpecDialog: Object,
    isOpenTime: Boolean
  },
  data: {
    num: 0
  },
  observers: {
    'cartList': function (cartList) {
      let num = 0;
      for (let item of cartList) {
        if (item.id === this.data.goods.id) {
          num = num + item.count;
        }
      }
      this.setData({num: num})
    }
  },
  methods: {
    handleOp(e) {
      let op = e.currentTarget.dataset.op
      const item = {};
      item.name = this.data.goods.name;
      item.price = this.data.goods.price;
      item.id = this.data.goods.id;
      item.spec = "";
      item.attrList = [];
      if (op === 'add') {
        this.addCart(item);
      } else {
        this.reduceCart(item);
      }
    },
    handleShowImg(e) {
      let imgUrl = e.currentTarget.dataset.img;
      wx.previewImage({
        current: '',
        urls: [imgUrl]
      })
    },
    handleShowSpecDialog() {
      // 规格选择组件在父级页面
      this.triggerEvent('selectspec', {goods: this.data.goods})
    }
  }
});
